/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package plugins.lcdstation.gui;

import helper.Proxy;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JToggleButton;

import base.AppMemory;

import dao.CityDAO;
import dao.DBException;

import metar.MetarInfo;
import metar.MetarLogException;
import metar.MetarParseException;
import metar.MetarReader;
import model.CityModel;
import model.CountryModel;
import model.WeatherModel;

import plugins.lcdstation.Wetterstation;
import plugins.lcdstation.io.ExDisplay;

/**
 * 
 * @author Hansj�rg
 */
public class MainFrame extends javax.swing.JFrame {

	private Timer timer = new Timer();

	private javax.swing.JTextField jtxt1;
	private javax.swing.JTextField jtxt2;
	private javax.swing.JTextField jtxt3;
	private javax.swing.JTextField jtxt4;
	private javax.swing.JToggleButton jtglBacklight;
	private javax.swing.JComboBox<CityModel> jcboxCityModel;

	private TimerTask task = new TimerTask() {

		@Override
		public void run() {

			jtglBacklight.setEnabled(false);
			jcboxCityModel.setEnabled(false);
			int i = jcboxCityModel.getSelectedIndex();

			if (i < jcboxCityModel.getItemCount() - 1) {
				i++;
			} else {
				i = 0;
			}

			jcboxCityModel.setSelectedIndex(i);

			jcboxCityModel.repaint();

			Object selectedItem = jcboxCityModel.getSelectedItem();
			if (selectedItem != null) {
				CityModel city = (CityModel) selectedItem;

				jtxt4.setText(city.getCountryName());
				jtxt1.setText(city.getName());
				jtxt2.setText(String.valueOf(city.weather.getTemperature())
						+ " Celcius");
				jtxt3.setText(String.valueOf(String.format("%1$TD %1$TT",
						city.weather.getTimeStamp())));

				SendDataToDisplay();
			}

			jtglBacklight.setEnabled(true);
			jcboxCityModel.setEnabled(true);
		}

	};

	// Initialisierung
	public MainFrame() throws IOException, InterruptedException {
		/**
		 * Config.ini laden
		 */
		if (!AppMemory.loadConfig()) {
			System.exit(0);
		}

		/**
		 * ggf. Proxy setzen
		 */
		Proxy.setProxy();
		
		ExDisplay.SetBacklight(true);
		InitializeComponent();

		this.jtglBacklight.setSelected(true);

		timer.scheduleAtFixedRate(task, 0, 10000);
	}

	private void InitializeComponent() {
		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		InitializeTglBacklight();
		InitializeTextBoxes();
		InitializeComboBoxes();

		// Mit etwas unterstützung vom Netbeas GUI-Designer :)

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		this.setLayout(layout);

		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addGroup(
														layout.createSequentialGroup()
																.addComponent(
																		jcboxCityModel,
																		javax.swing.GroupLayout.PREFERRED_SIZE,
																		200,
																		javax.swing.GroupLayout.PREFERRED_SIZE)
																.addGap(85, 85,
																		85)
																.addComponent(
																		jtglBacklight,
																		javax.swing.GroupLayout.PREFERRED_SIZE,
																		43,
																		javax.swing.GroupLayout.PREFERRED_SIZE))
												.addComponent(
														jtxt2,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														260,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(
														jtxt4,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														260,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(
														jtxt3,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														260,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(
														jtxt1,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														260,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addContainerGap(
										javax.swing.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));

		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING,
												false)
												.addComponent(
														jtglBacklight,
														javax.swing.GroupLayout.Alignment.TRAILING,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														Short.MAX_VALUE)
												.addComponent(
														jcboxCityModel,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														Short.MAX_VALUE))
								.addGap(33, 33, 33)
								.addComponent(jtxt4,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(jtxt2,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addGap(4, 4, 4)
								.addComponent(jtxt1,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(jtxt3,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addContainerGap(
										javax.swing.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));

		pack();
	}

	private ArrayList<CityModel> GetCities() {
		
		ArrayList<CityModel> result = new ArrayList<CityModel>();

		String[] airports = { "EDDS", "KLOZ", "EDDI", "EHAM", "EDDM", "CYMX", "PADK", 
				"PADL", "PACV", "PABR", "GMMX", "HKMO", "KDAL", "LTAC", "MMAA", "MMMX" };

		for (String s : airports) {
			try {

				/**
				 * Die daten der Flughäfen abfragen
				 */
				System.out.println("get weather for: " + s + "...");
				WeatherModel wm = new MetarReader(s).getMetarInfo();

				CityModel city = new CityDAO().readCity(wm.getCityID());
				city.weather = wm;
				result.add(city);
			} catch (MetarLogException e) {
				if (MetarInfo.isDebugMode()) {
					e.printStackTrace();
				}
				JOptionPane.showMessageDialog(null, e.getMessage(),
						"Error while writing logfile",
						JOptionPane.ERROR_MESSAGE);
				System.exit(0);
			} catch (MetarParseException e) {
				if (MetarInfo.isDebugMode()) {
					e.printStackTrace();
				}
				JOptionPane.showMessageDialog(null, e.getMessage(),
						"Error while parsing metar info",
						JOptionPane.ERROR_MESSAGE);
				System.exit(0);
			} catch (DBException e) {
				if (MetarInfo.isDebugMode()) {
					e.printStackTrace();
				}
				JOptionPane.showMessageDialog(null, e.getMessage(), "DB Error",
						JOptionPane.ERROR_MESSAGE);
				System.exit(0);
			}
		}

		return result;
	}

	private void InitializeComboBoxes() {
		jcboxCityModel = new JComboBox<CityModel>();

		jcboxCityModel.setPreferredSize(new Dimension(200, 30));

		for (CityModel city : this.GetCities()) {
			jcboxCityModel.addItem(city);
		}

		jcboxCityModel.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (jcboxCityModel.isEnabled()) {
					int i = jcboxCityModel.getSelectedIndex();
					if(i > 0) {
						i--;
					}
					else {
						i = jcboxCityModel.getItemCount() - 1;
					}
					jcboxCityModel.setSelectedIndex(i);
					
					timer.cancel();
					timer.purge();
					timer = new Timer();
					timer.scheduleAtFixedRate(new TimerTask() {

						@Override
						public void run() {

					//		jbtnSend.setEnabled(false);
							jtglBacklight.setEnabled(false);
							jcboxCityModel.setEnabled(false);
							int i = jcboxCityModel.getSelectedIndex();

							if (i < jcboxCityModel.getItemCount() - 1) {
								i++;
							} else {
								i = 0;
							}

							jcboxCityModel.setSelectedIndex(i);

							jcboxCityModel.repaint();

							Object selectedItem = jcboxCityModel.getSelectedItem();
							if (selectedItem != null) {
								CityModel city = (CityModel) selectedItem;

								jtxt4.setText(city.getCountryName());
								jtxt1.setText(city.getName());
								jtxt2.setText(String.valueOf(city.weather.getTemperature())
										+ " Celcius");
								jtxt3.setText(String.valueOf(String.format("%1$TD %1$TT",
										city.weather.getTimeStamp())));

								SendDataToDisplay();
							}
					//		jbtnSend.setEnabled(true);
							jtglBacklight.setEnabled(true);
							jcboxCityModel.setEnabled(true);
						}

					}, 0, 10000);
				}
			}
		});

		this.getContentPane().add(jcboxCityModel);
	}

	private void SendDataToDisplay() {
		try {
			Wetterstation.SendToExDisplay(jtxt1.getText(), jtxt2.getText(),
					jtxt3.getText(), jtxt4.getText());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void InitializeTglBacklight() {
		jtglBacklight = new JToggleButton();
		jtglBacklight.setIcon(new javax.swing.ImageIcon(getClass().getResource(
				"/plugins/lcdstation/gui/Backlight_32.png"))); // NOI18N
		jtglBacklight.setToolTipText("Hintergrundbeleuchtung");
		jtglBacklight.setText("");
		jtglBacklight.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jtglBacklightActionPerformed(evt);
			}
		});
	}

	private void InitializeTextBoxes() {
		jtxt1 = new JTextField();
		jtxt2 = new JTextField();
		jtxt3 = new JTextField();
		jtxt4 = new JTextField();
	}

	// Buttons:
	private void jtglAutomaticctionPerformed(ActionEvent evt) {
		// TODO Automatische Übertragung
	}

	private void jtglBacklightActionPerformed(ActionEvent evt) {
		try {
			ExDisplay.SetBacklight(jtglBacklight.isSelected());
		} catch (IOException ex) {
			JOptionPane.showMessageDialog(this, ex,
					"Fehler beim setzen der Hintergrundbeleuchtung!",
					JOptionPane.ERROR_MESSAGE);
			Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null,
					ex);
		}
	}

}
